<?php

namespace App\Admin\Forms;

use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;

class IPSearch extends Form
{
    /**
     * The form title.
     *
     * @var string
     */
    public $title = 'IP查询';

    /**
     * Handle the form request.
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request)
    {
        $ip = $request->get('ip');
        $type = $request->get('type');
        $count = $request->get('count');
        $count++;
        $map = [
          1=>'json',
          2=>'plain'
        ];
        $url = 'http://ip-api.com/'.$map[$type].'/'.$ip;
        $result = $this->curlGet($url);
        if(!$result){
            $result = 'request time out';
        }
        $str = 'country';
        if(strstr(json_encode($result),$str) !== false || $count === 9){
            $result = '@查询失败';
        }
        //admin_success('Processed successfully.');
        return back()->with(['result'=>$result,'data'=>['ip'=>$ip,'type'=>$type],'count'=>$count]);
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->action('#')->attribute(['name'=>'ip_search']);
        $this->ip('IP')->attribute(['name'=>'ip'])->rules('required');
        $this->select('type')->attribute(['name'=>'type'])->options([1 => 'json', 2 => 'plain'])->rules('required');
        $this->hidden('count')->attribute(['name'=>'count'])->value(0);
        $this->textarea('result');
    }

    /**
     * The data of the form.
     *
     * @return array $data
     */
    public function data()
    {
        return [
            'IP'       => '',
            'type'      => null,
        ];
    }

    public function curlGet($url)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT,5);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
}
